<?php

namespace App\Http\Requests\Admin\PayAndConsume;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;

class HotspotUploadRequest extends FormRequest
{
    protected function validationData()
    {
        return count($this->json()->all()) ? $this->json()->all() : $this->all();
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'game_id' => 'required',
            'channel_id' => 'required',
            'action_id' => 'required',
            'op_time' => 'required',
            'device_id' => 'required_if:action_id,1,2',
            'uid' => 'required_unless:action_id,1,2',
        ];
    }

    public function messages()
    {
        return [
            'game_id.required' => 'game_id不能为空',
            'channel_id.required' => 'channel_id不能为空',
            'action_id.required' => 'action_id不能为空',
            'op_time.required' => 'op_time不能为空',
            'device_id.required_if' => 'action_id为1,2时,device_id不能为空',
            'uid.required_unless' => 'action_id不为1,2时,uid不能为空',
        ];
    }

    protected function prepareForValidation()
    {
        $result = count($this->json()->all()) ? $this->json()->all() : $this->all();
        $this->replace($result);
    }

    protected function failedValidation(Validator $validator)
    {
        $error = $validator->errors()->all();
        $error = implode('|', $error);

        $return = returnArr('-1', $error);
        throw new HttpResponseException(
            response()->json($return, JsonResponse::HTTP_UNPROCESSABLE_ENTITY)
        );
    }
}
